<template>
<div>
  <uploaderNew ref="uploaderNew" @updateValue='updateValue' @uploadSuccess="uploadSuccess" :disabled="disabled" :progress="progress" @progress="progressFn" :item="item" @remove='remove' :list="list" v-bind="$attrs"></uploaderNew>
</div>
</template>

<script lang="ts">
import { Component, Mixins, Prop } from 'vue-property-decorator';
import uploaderNew from '@/afterSales/components/uploader/uploader.vue';
import widgetCommon from '../common/widgetCommon';
import { uploadQiniu } from '@/utils/upload'
// eslint-disable-next-line no-restricted-imports
import { clone } from 'lodash';
import { uuid } from '@/utils/common';
@Component({
  name: 'accessory',
  components: {
    uploaderNew
  }
})
export default class extends Mixins(widgetCommon) {
  @Prop({ default: true }) private paste!: boolean;
  private progress: any = [];
  private $message: any;
  private get list () {
    const list = clone(this.value || []);
    if (this.item.arrangeType === 2) {
      list.reverse();
    }
    return list;
  }

  private remove (item) {
    // this.value = this.value.filter((file) => file.url !== item.url)
    this.changeValue(this.value.filter((file) => file.url !== item.url));
    // this.tableChangeValue()
  }

  private progressFn (data) {
    console.log(data);
    this.progress = data;
  }

  private uploadSuccess (file, fieldList?) {
    this.changeValue([file, ...(this.value || [])]);
  }

  // 提交数据
  private updateValue (val) {
    this.changeValue(val);
  }

  // 监听粘贴事件
  private handlePaste (event) {
    const items = event.clipboardData && event.clipboardData.items;
    let file: any = null;
    if (items && items.length) {
      for (let i = 0; i < items.length; i++) {
        file = items[i].getAsFile();
        // if (items[i].type.indexOf('image') !== -1) {
        //   file = items[i].getAsFile();
        // }
      }
    }
    if (!(this.$refs as any).uploaderNew.beforeUpload(file)) {
      return false
    }
    const request = {
      file,
      onProgress: this.onProgress,
      onError: this.onError,
      onSuccess: this.onSuccess
    }
    uploadQiniu({ type: 'crm', fileName: file.name }, request)
    if (!file) {
      this.$message.warning('当前仅支持粘贴图片格式附件');
      return;
    }
    this.uploadFiles(async () => await this.upImageToken(file));
  }

  private onSuccess (response: any, file: any) {
    const uploadFile = {
      url: response.domain + '/' + response.key,
      fileName: file.name
    };
    this.progressFn([]);
    this.uploadSuccess(uploadFile);
  }

  private onProgress (e: any, file: any) {
    if (e.percent > 0) {
      const oldName = file.name.split('.');
      const percentage = Math.floor((e.loaded / e.percent) * 100);
      const name = oldName[0];
      const suffix = oldName[1];
      this.progressFn([{ percentage, name, fileName: name, suffix }]);
    }
  }

  private onError () {
    console.log('aaa')
  }

  // 获取上传图片秘钥
  public async upImageToken (file) {
    let token;
    return {
      token,
      file
    };
  }

  private processList (list) {
    return list
      .filter((item) => {
        return item.status !== 'ready' && item.percentage < 100;
      })
      .map(({ name, percentage }) => {
        return { name, percentage: Math.floor(percentage) };
      });
  }

  // 上传图片
  private async uploadFiles (upImageToken) {
    const { file, key, token } = await upImageToken();
    const formData = new FormData();
    formData.append('file', file);
    formData.append('key', key);
    formData.append('token', token);
    // imageService({
    //   method: 'post',
    //   responseType: 'json',
    //   onUploadProgress: (e) => {
    //     // 对原生进度事件的处理
    //     if (e.total > 0) {
    //       const oldName = file.name.split('.');
    //       const percentage = Math.floor((e.loaded / e.total) * 100);
    //       const name = oldName[0];
    //       const suffix = oldName[1];
    //       this.progressFn([{ percentage, name, suffix }]);
    //     }
    //   },
    //   data: formData
    // }).then((response) => {
    //   const uploadFile = {
    //     url: response.data.key,
    //     fileName: file.name,
    //     createTime: new Date()
    //   };
    //   this.progressFn([]);
    //   this.uploadSuccess(uploadFile);
    // });
  }

  public async mounted () {
    if (this.paste) {
      document.addEventListener('paste', this.handlePaste);
    }
  }

  public destroyed () {
    if (this.paste) {
      document.removeEventListener('paste', this.handlePaste);
    }
  }
}
</script>

<style lang="stylus" scoped>
.default-value {
	right 0
	top -30px
	position absolute
}
</style>
